﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OracleClient;
using System.Text;
using StandardDAC.Base;

namespace StandardDAC.OracleClient {
    internal class OracleDBTypeAdapter : IDBTypeAdapter {
        #region IDBTypeAdapter Members

        public DbCommand NewCommand(string commandText, DbConnection connection, ConnOrTranInfo conn) {
            OracleCommand cmd = new OracleCommand(commandText, (OracleConnection)connection);
            if (conn is TranInfo)
                cmd.Transaction = (OracleTransaction)((TranInfo)conn).Transaction;
            return cmd;
        }

        public DbConnection NewConnection(ConnOrTranInfo conn) {
            if (conn is ConnInfo) {
                OracleConnection c = new OracleConnection(((ConnInfo)conn).ConnectionString);
                c.Open();
                return c;
            } else
                return ((TranInfo)conn).Transaction.Connection;
        }

        public DbDataAdapter NewAdapter(DbCommand command) {
            return new OracleDataAdapter((OracleCommand)command);
        }

        public DbParameter AddNewParameter(string name, object dbType, DbCommand command) {
            return ((OracleCommand)command).Parameters.Add(name, (OracleType)dbType);
        }
        /// <summary>
        /// Not needed. Does nothing
        /// </summary>
        /// <param name="command"></param>
        public void SortParametersIfNeeded(Dictionary<string, KeyValuePair<int, DBColumn>> parametersToSort, DbCommand cmd) {
        }

        public DbParameter AddNewNullParameter(string name, DbCommand command) {
            return ((OracleCommand)command).Parameters.AddWithValue(name, DBNull.Value);
        }

        public DbParameter AddExistingParameter(DbParameter param, DbCommand command) {
            return ((OracleCommand)command).Parameters.Add((OracleParameter)param);
        }

        public string ConvertNameToParam(string columnName) {
            return ":" + columnName;
        }

        public void PreExecute(DbCommand command) {
        }

        public void AddOutputCursorIfNeeded(DbCommand command, Type type) {
            object[] ary = type.GetCustomAttributes(typeof(OracleReadCursor), true);
            if (ary.Length >= 1){
                OracleReadCursor outputCursor = (OracleReadCursor)ary[0];
                ((OracleCommand)command).Parameters.Add(ConvertNameToParam(outputCursor.Name), OracleType.Cursor).Direction = ParameterDirection.Output;
            }
        }
        #endregion
    }
}
